<template>
  <div>
    <h4>发表评论</h4>
    <hr>
    <textarea rows="3" placeholder="请输入评论内容，最多输入120字" maxlength="120" v-model="content" @keyup.enter="postComment"></textarea>
    <mt-button type="primary" size="large" @click="postComment" >发表评论</mt-button>

    <div class="cmt-list">
      <div v-for="(item, i) in list" :key="i">
        <div class="cmt-info">
          <span>第{{i+1}}楼</span>&nbsp;&nbsp;
          <span>用户：{{item.user_name}}</span>&nbsp;&nbsp;
          <span>发表时间：{{item.add_time | dateFormat}}</span>&nbsp;&nbsp;
        </div>
        <div class="cmt-content">{{item.content}}</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>


<script>

import { Toast } from 'mint-ui';

export default {
  data() {
    return {
      list: [],
      content:"",
      pageindex:1
    }
  },
  props:["id"],
  created() {
    this.getCommentList();
  },
  methods: {
    getCommentList() {
      // 拿到父组件属性传递过来的id --- console.log(this.id);
      this.$http.get("api/getcomments/"+this.id+"?pageindex="+this.pageindex).then(res=>{
      //  console.log(res.body);
       if(res.body.status===0) {
         if(res.body.message.length===0) {
           Toast('亲，没有更多评论了！');
           return;
         }
        this.list = this.list.concat(res.body.message);
       }else {
          Toast('获取评论数据失败！');
       }
      })
    },
    getMore() {
      this.pageindex++;
      // 调用获取评论函数
      this.getCommentList();
    },
    postComment() {
      this.$http.post("api/postcomment/"+this.id,{content:this.content},{emulateJSON:true}).then(res=>{
        // console.log(res.body);
        if(res.body.status===0) {
          // 将评论插入评论列表的最前面
          this.list.unshift({ 
            user_name: '匿名用户', 
            add_time: new Date(), 
            content: this.content 
          })
          Toast('发表评论成功！');
          // 清空
          this.content = "";
        }else{
           Toast('评论发表失败！');
        }
      })
    }
  }
}
</script>


<style lang = "scss" scoped >
  textarea {
  margin: 0;
  font-size: 14px;
}

.cmt-list {
  margin: 5px 0;
}

.cmt-info {
  font-size: 13px;
  background-color: #ccc;
  line-height: 30px;
  text-indent: 3px;
  border-radius: 5px;
  color:#fff;
}

.cmt-content {
  line-height: 40px;
  font-size: 14px;
  text-indent: 2em;
}
</style>